import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';

import { ICoupons } from 'app/shared/model/coupons.model';
import { CouponsService } from './coupons.service';

@Component({
    selector: 'jhi-coupons-update',
    templateUrl: './coupons-update.component.html'
})
export class CouponsUpdateComponent implements OnInit {
    coupons: ICoupons;
    isSaving: boolean;

    constructor(protected couponsService: CouponsService, protected activatedRoute: ActivatedRoute) {}

    ngOnInit() {
        this.isSaving = false;
        this.activatedRoute.data.subscribe(({ coupons }) => {
            this.coupons = coupons;
        });
    }

    previousState() {
        window.history.back();
    }

    save() {
        this.isSaving = true;
        if (this.coupons.id !== undefined) {
            this.subscribeToSaveResponse(this.couponsService.update(this.coupons));
        } else {
            this.subscribeToSaveResponse(this.couponsService.create(this.coupons));
        }
    }

    protected subscribeToSaveResponse(result: Observable<HttpResponse<ICoupons>>) {
        result.subscribe((res: HttpResponse<ICoupons>) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError());
    }

    protected onSaveSuccess() {
        this.isSaving = false;
        this.previousState();
    }

    protected onSaveError() {
        this.isSaving = false;
    }
}
